﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;



using OF.Component.Model;
using OF.Utility;
using OF.Utility.Logging;
using System.Text;
using System.Xml.XPath;
using CWQ.Api.Common;
using CWQ.Api.Models;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OF.AppContext;
using OF.Component.Base;
using OF.Component.BLL;
using OF.Component.DTO;
using Swashbuckle.Swagger.Annotations;
using System.IO;
using System.Web;
using System.Threading.Tasks;

namespace CWQ.Api.Controllers
{
    /// <summary>
    /// 测试控制器
    /// </summary>
    public class ShopController : BaseApiController
    {
        /// <summary>
        /// 获取微信OpenID
        /// </summary>
        /// <param name="code"></param>
        [HttpGet]
        public ResultData<ResponseGetWxLoginInfo> GetWxLoginInfo(string code)
        {
            var result = ResultData<ResponseGetWxLoginInfo>.Error("");
            string tplApi = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
            string urlApi = string.Format(tplApi, AppSettings.WxAppID, AppSettings.WxAppSecret, code);
            string szContent = "";
            if (RequestHelper.GetHtml(urlApi, "get", Encoding.UTF8, out szContent))
            {
                JObject oJson = (JObject)JsonConvert.DeserializeObject(szContent);
                var errorCodeNode = oJson.Properties().FirstOrDefault(m => m.Name == "errcode");
                if (errorCodeNode != null)
                {
                    var errmsgNode = oJson.Properties().FirstOrDefault(m => m.Name == "errmsg");
                    if (errmsgNode != null)
                    {
                        //result = ResultData<int>.Error(errmsgNode.Value.ToString());
                        LogClient.Current.Error("获取微信OpenID时失败：" + errmsgNode.ToString());
                        result = ResultData<ResponseGetWxLoginInfo>.Error("获取用户信息失败");
                    }
                }
                else
                {
                    var data = szContent.JSONToObject<VmGetOpenID>();
                    string szEncryptOpenId = DES.Instance.EncryptUrl(data.openid);
                    string szEncrptSessionKey = DES.Instance.EncryptUrl(data.session_key);
                    ResponseGetWxLoginInfo oInfo = new ResponseGetWxLoginInfo();
                    var oShop = ShopOperate.QuerySingle(m => m.WxOpenID == data.openid);
                    if (oShop != null)
                    {
                        oInfo.ShopID = oShop.ShopID;
                    }
                    oInfo.OpenId = szEncryptOpenId;
                    oInfo.WxSessionKey = szEncrptSessionKey;
                    result = ResultData<ResponseGetWxLoginInfo>.Success(oInfo);
                }
            }
            return result;

        }

        /// <summary>
        /// 创建店铺请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultData<ResponseCreateShop> CreateShop(RequestCreateShop request)
        {
            ResultData<ResponseCreateShop> result = ResultData<ResponseCreateShop>.Error("");
            //判断验证码是否正确
            if (!SendMessage.CheckVerificationCode(request.Mobile, request.VerifyCode, AppSettings.ShortMessagePlatformId, AppSettings.ShortMessageUrl))
            {
                result = ResultData<ResponseCreateShop>.Error("验证码错误");
                return result;
            }
            var oShop = ShopOperate.QuerySingle(m => m.Mobile == request.Mobile);

            if (oShop != null)
            {
                result = ResultData<ResponseCreateShop>.Error("该手机号已注册，请勿重复注册 。");
                return result;
            }

            var decryptOpenId = DES.Instance.DecryptUrl(request.WxOpenID);
            var oModel = new ShopInfo();

            request.MergeTo(oModel);
            oModel.CreatedDate = DateTime.Now;
            oModel.WxOpenID = decryptOpenId;
            oModel.IsActive = 1;

            int nReturn = ShopOperate.Insert(oModel);
            //保存店铺照片
            if (request.ShopImgs != null && request.ShopImgs.Count > 0)
            {
                var list = request.ShopImgs;
                list.ForEach((item) =>
                {
                    var oImgInfo = new ShopImgInfo()
                    {
                        ShopID = nReturn,
                        ImgUrl = item
                    };
                    ShopImgOperate.Insert(oImgInfo);
                });

            }
            if (nReturn > 0)
            {
                result = ResultData<ResponseCreateShop>.Success(new ResponseCreateShop()
                {
                    ShopID = nReturn
                });
            }
            return result;
        }


        ///// <summary>
        ///// 获取店铺摘要信息，对应“我的”页面
        ///// </summary>
        ///// <returns></returns>
        //public ResultData<ResponseGetShopSummary> GetShopSummary()
        //{
        //    var shopID = UserContext.Current.UserID;
        //    var result = ResultData<ResponseGetShopSummary>.Error("");

        //    var response = GetShopSummaryByShopId(shopID);
        //    if (response != null)
        //    {
        //        result = ResultData<ResponseGetShopSummary>.Success(response);
        //    }
        //    return result;

        //}

        /// <summary>
        /// 获取店铺摘要信息
        /// </summary>
        /// <returns></returns>
        public ResultData<ResponseGetShopSummary> GetShopSummary(int shopId)
        {
            var result = ResultData<ResponseGetShopSummary>.Error("");

            var response = GetShopSummaryByShopId(shopId);
            if (response != null)
            {
                result = ResultData<ResponseGetShopSummary>.Success(response);
            }
            return result;
        }

        private ResponseGetShopSummary GetShopSummaryByShopId(int shopID)
        {
            var oShop = ShopOperate.GetByID(shopID);
            if (oShop != null)
            {
                var response = new ResponseGetShopSummary();
                string szHeadImgSrc = "";

                if (oShop.HeadImgSrcType == 1)
                {
                    szHeadImgSrc = oShop.HeadImgSrc;
                }
                else if (oShop.HeadImgSrcType == 2)
                {
                    szHeadImgSrc = GetHttpFilePath(oShop.HeadImgSrc);
                }
                var listSend = PostSendOperate.QueryList(m => m.ShopID == shopID);
                var listReceive = PostReceiveOperate.QueryList(m => m.ShopID == shopID);
                int nCount = listSend.Count + listReceive.Count;
                response.ShopID = oShop.ShopID;
                response.UserName = oShop.UserName;
                response.ShopName = oShop.ShopName;
                response.HeadImgSrc = szHeadImgSrc;
                response.PostCount = nCount;
                return response;
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResultData<ResponseGetShopDetail> GetShopDetail(int shopId)
        {
            var result = ResultData<ResponseGetShopDetail>.Error("");
            var oInfo = ShopOperate.GetByID(shopId);
            var response = new ResponseGetShopDetail();
            if (oInfo != null)
            {
                oInfo.MergeTo(response);
                string szShopTypeName = "";
                string szCityName = "";
                if (oInfo.ShopType == 1)
                {
                    szShopTypeName = "企业";
                }
                else if (oInfo.ShopType == 2)
                {
                    szShopTypeName = "个人";
                }
                var oLocation = BaseLocation_AllOperate.GetByID(oInfo.LocationId);
                if (oLocation != null)
                {
                    szCityName = oLocation.PName + "-" + oLocation.CName + "-" + oLocation.LocationName;
                    response.ProvinceId = oLocation.Pid;
                    response.CityId = oLocation.CId;
                    response.CountyId = oLocation.LocationId;
                }
                var resListImg = new List<ShopImageModel>();
                var listImg = ShopImgOperate.QueryList(m => m.ShopID == shopId);
                // resListImg = listImg.Select(m => GetHttpFilePath(m.ImgUrl)).ToList();
                listImg.ForEach(a => {
                    var obj = new ShopImageModel()
                    {
                        HttpImgUrl = GetHttpFilePath(a.ImgUrl)
                    };
                    a.MergeTo(obj);
                    resListImg.Add(obj);
                });
                response.ShopTypeName = szShopTypeName;
                response.CityName = szCityName;
                response.ShopImgs = resListImg;
                response.MapLocationAddress = oInfo.MapLocationAddress;
                response.ShopTypeId = oInfo.ShopType;
                string imgSrc = oInfo.HeadImgSrcType == 1 ? oInfo.HeadImgSrc : GetHttpFilePath(oInfo.HeadImgSrc);
                response.HeadImgSrcArr = new string[]{ imgSrc, oInfo.HeadImgSrc};
               
                result = ResultData<ResponseGetShopDetail>.Success(response);
            }
            return result;
        }

        /// <summary>
        /// 修改手机号发送验证码
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<string> CheckModfiyMobileRepeat(string mobile)
        {
            ResultData<string> rData = new ResultData<string>();
            var oShop = ShopOperate.QuerySingle(a => a.Mobile == mobile);
            if (oShop != null)
            {

                rData.status = -1;
                rData.message = "手机号已注册";
                return rData;

            }
            return rData;
        }

        /// <summary>
        /// 更改手机号
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> ModfiyMobile(CheckMobileModel model)
        {
            ResultData<int> rData = new ResultData<int>();
            bool result = SendMessage.CheckVerificationCode(model.Mobile,model.VerifyCode, AppSettings.ShortMessagePlatformId, AppSettings.ShortMessageUrl);
            if (result)
            {
                var shopID = UserContext.Current.UserID;
                var oShop = ShopOperate.GetByID(shopID);
                if (oShop != null)
                {
                    oShop.Mobile = model.Mobile;
                    ShopOperate.Update(oShop);
                    rData.message = "更新成功";
                    rData.data = shopID;
                }
            }else
            {
                rData.status = -1;
                rData.message = "验证码错误";

                //添加错误日志
                LogClient.Current.Error(new ErrorLog()
                {
                    ErrorMessage = "验证码错误",
                    PlatformID = 1,
                    RequestUrl = "Shop/ModfiyMobile",
                    PostData = string.Format("Mobile{0},VerificationCode{1}", model.Mobile, model.VerifyCode)
                });
            }
            return rData;
        }

        /// <summary>
        /// 更新店铺信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<ResponseCreateShop> UpdateShop(RequestCreateShop request)
        {
            ResultData<ResponseCreateShop> result = ResultData<ResponseCreateShop>.Error("");
            var shopID = UserContext.Current.UserID;
            var oShop = ShopOperate.GetByID(shopID);
            if (oShop != null)
            {
                oShop.UserName = request.UserName;
                oShop.ShopType = request.ShopType;
                oShop.ShopName = request.ShopName;
                oShop.LocationId = request.LocationId;
                oShop.MapLocationName = request.MapLocationName;
                oShop.Address = request.Address;
                oShop.MapLocationAddress = request.MapLocationAddress;
                oShop.Description = request.Description;
                oShop.MapLatitude = request.MapLatitude;
                oShop.MapLogitude = request.MapLogitude;
                ShopOperate.Update(oShop);
            }

            //保存店铺照片
            if (request.ShopImgs != null && request.ShopImgs.Count > 0)
            {
                ShopImgOperate.DeleteShopImgByShopId(shopID);
                var list = request.ShopImgs;
                list.ForEach((item) =>
                {
                    var oImgInfo = new ShopImgInfo()
                    {
                        ShopID = shopID,
                        ImgUrl = item
                    };
                    ShopImgOperate.Insert(oImgInfo);
                });

            }

            result = ResultData<ResponseCreateShop>.Success(new ResponseCreateShop()
            {
                ShopID = shopID
            });

            return result;
        }

        /// <summary>
        ///更新头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Task<string> UpdateUserHeadImage()
        {
            // 确定指定的内容是否是 MIME 多部分内容
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string shopId = HttpContext.Current.Request["shopId"];

            //指定要将文件存入的服务器物理位置  
            string certificatePath = AppSettings.UploadFileDir;
            var szHttpFileFullPath = AppSettings.UploadFileFullHttpDir;
            var szHttpFileRelativePath = AppSettings.UploadFileRelativeHttpDir;
            if (!Directory.Exists(certificatePath))
            {
                Directory.CreateDirectory(certificatePath);
            }
            var provider = new MultipartFormDataStreamProvider(certificatePath);

            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<string>(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }

                    
                    string fileName = "";
                    //获取上传文件
                    foreach (MultipartFileData file in provider.FileData)
                    {
                        //api默认保存的文件没有后缀名,需要重命名
                        FileInfo f = new FileInfo(file.LocalFileName);
                        int idx = file.Headers.ContentDisposition.FileName.LastIndexOf('.');
                        string pfx = file.Headers.ContentDisposition.FileName.Substring(idx).Replace("\"", string.Empty);
                        //api的文件名,自动添加了双引号(")，此处去掉，否则会提示非法路径。  真坑
                        string newFileName = file.LocalFileName.Replace("_", string.Empty).Replace("-", string.Empty);
                        string newFileNamePfx = newFileName + pfx;
                        f.MoveTo(newFileNamePfx);
                        fileName = newFileNamePfx.Substring(newFileName.LastIndexOf("\\") + 1);
                    }
                    var imgFullPath = szHttpFileFullPath + fileName;
                    var imgRelativePath = szHttpFileRelativePath + fileName;
                    var oShop = ShopOperate.GetByID(int.Parse(shopId));
                    if (oShop!=null)
                    {
                        oShop.HeadImgSrc = imgRelativePath;
                        oShop.HeadImgSrcType = 2;
                        ShopOperate.Update(oShop);
                    }

                  
                    var result = new ResponseUpload()
                    {
                        FileHttpFullPath = imgFullPath,
                        FileRelativeFullPath = imgRelativePath
                    }.ToJSON();
                    return result;
                });
            return task;
        }

        /// <summary>
        /// 删除店铺展示图片
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<bool> DelShopImageById(ShopImageParamModel model) {
            ResultData<bool> result = ResultData<bool>.Error("");
            try
            {
                ShopImgInfo info = ShopImgOperate.GetByID(model.ShopImgId);
                if (info != null)
                {
                    ShopImgOperate.Delete(model.ShopImgId);
                    result.status = 0;
                    result.message = "删除成功";
                    result.data = true;
                }
                else
                {
                    result.message = "查不到此图片";
                    result.data = false;
                }
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
            }
            return result;
        }

    }
}
